﻿using System.Linq.Dynamic.Core;

namespace TrackSystem.EntityFramework.Repositories.Extensions
{
    public static class RepositoryExtensions
    {
        public static IQueryable<T> OrderByQuery<T>(this IQueryable<T> source, string? queryString)
        {
            if (string.IsNullOrWhiteSpace(queryString))
            {
                return source;
            }

            if (source == null)
            {
                return source;
            }

            var orderParams = queryString.Trim().Split(',');
            var propertyInfos = typeof(T).GetProperties(
                  System.Reflection.BindingFlags.IgnoreCase
                | System.Reflection.BindingFlags.Public
                | System.Reflection.BindingFlags.Instance);
            if (propertyInfos == null)
            {
                throw new ArgumentException($"Property '{queryString}' does not exist on type '{typeof(T).Name}'.");
            }

            var orderQueryBuilder = new System.Text.StringBuilder();
            foreach (var param in orderParams)
            {
                if (string.IsNullOrWhiteSpace(param))
                {
                    continue;
                }

                var propertyFromQueryName = param.Trim().Split(' ')[0];
                var objectProperty = propertyInfos.FirstOrDefault(
                    pi =>
                    pi.Name.Equals(propertyFromQueryName,
                    StringComparison.OrdinalIgnoreCase));
                if (objectProperty == null)
                    continue;

                var sortingOrder = param.EndsWith(" desc", StringComparison.OrdinalIgnoreCase) ? "descending" : "ascending";
                orderQueryBuilder.Append($"{objectProperty.Name} {sortingOrder}, ");
            }
            var orderQuery = orderQueryBuilder.ToString().TrimEnd(',', ' ');
            return source.OrderBy(orderQuery);
        }
    }
}
